package com.probiz.estoresa.theme.web.action;

import com.probiz.estore.common.helper.ConfigUtil;
import com.probiz.estore.common.util.DateUtil;
import com.probiz.estore.content.util.ZipHelper;
import com.probiz.estore.webapp.util.RequestUtil;
import com.probiz.estoresa.theme.model.Theme;
import com.probiz.estoresa.theme.service.ThemeService;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

public class ThemeController extends MultiActionController {
    private ThemeService themeService=null;
    private MultipartResolver multipartResolver;

    private long							maxUploadSize		= 20 * 1024 * 1024;


    public void setMultipartResolver(MultipartResolver multipartResolver) {
        this.multipartResolver = multipartResolver;
    }

    public void setThemeService(ThemeService themeService) {
        this.themeService = themeService;
    }






    	public class FileInfo {
		private final static String	DEFAULT_CATEGORY	= "others";
		private String				category			= DEFAULT_CATEGORY;
		public String				fileNameOnly;
		private String				generatedPath;

		private String				suffix				= null;

		private String				url;

		public FileInfo(String category, String fileName) {
			if (category != null && !"".equals(category.trim())) {
				this.category = category;
			}
			int idx = fileName.lastIndexOf(".");
			if (idx > 0 && idx != fileName.length()) {
				suffix = fileName.substring(idx + 1, fileName.length())
						.toLowerCase();
				this.fileNameOnly = fileName.substring(0, idx);
			} else {
				this.fileNameOnly = fileName;
			}
		}

		public String appendSuffix(String suffix2) {
			StringBuilder sb = new StringBuilder(fileNameOnly);
			if (suffix2 != null && suffix2.trim().length() > 0) {
				sb.append("_").append(suffix2);
			}
			sb.append(".").append(suffix);
			return sb.toString();
		}

		public void autoRename() {
			fileNameOnly = fileNameOnly + "_"+ UUID.randomUUID().getLeastSignificantBits();
			generatedPath = null;
			url = null;
		}

		public String getFileName() {
			return new StringBuilder(fileNameOnly).append(".").append(suffix)
					.toString();
		}

		public String getGeneratedPath() {
			// 可能可以考虑加上用户的id进一步减少一级目录下的文件数
			if (generatedPath == null) {
				generatedPath = new StringBuilder(category).append("/").toString();
			}
			return generatedPath;
		}

		public String getRelativePathAndName() {
			return getRelativePathAndName(getFileName());
		}

		public String getRelativePathAndName(String fileName) {
			return new StringBuilder(getGeneratedPath()).append(fileName)
					.toString();
		}

		public String getSuffix() {
			return suffix;
		}

		public String getUrl() {
			if (url == null) {
				url = getUrl(getFileName());
			}
			return url;
		}

		public String getUrl(String fileName) {
			return new StringBuilder(getGeneratedPath()).append(
					encodeUrl(fileName)).toString();
		}
	}

    	protected String encodeUrl(String fileName) {
		return fileName;
	}

	protected String getFullFilePath(String relativePath) {
		return new StringBuilder(ConfigUtil.getInstance().getMediaUploadPath()).append("/").append(
				relativePath).toString();
	}



    public ModelAndView defaultAction(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

      String installPath= ConfigUtil.getInstance().getStoreFrontInstallationPath();
      String themePath=installPath+"/themes/";

        List<Theme>  themeList=themeService.getThemeList(themePath);

      request.setAttribute("themeList",themeList);
        
      return new ModelAndView("/theme/themeList");
	}
    public ModelAndView activeTheme(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
      String themeName = request.getParameter("themeName");

       themeService.activeTheme(themeName); 

      return new ModelAndView("redirect:/content/theme.html");
	}

    public ModelAndView addTheme(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

      return new ModelAndView("/theme/addTheme");
	}
    public ModelAndView deleteTheme(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
      String themeName = request.getParameter("themeName");

       themeService.deleteTheme(themeName); 
      return new ModelAndView("redirect:/content/theme.html");
	}

     public ModelAndView uploadTheme(HttpServletRequest request,HttpServletResponse response) throws Exception {

        MultipartHttpServletRequest fileRequest = null;
		String uploadMsg = "";
		String filePath = null;
		if (multipartResolver.isMultipart(request)) {

			try {
				fileRequest = multipartResolver.resolveMultipart(request);
				Iterator<String> iter = fileRequest.getFileNames();
				while (iter.hasNext()) {
					String prmName = iter.next();
					MultipartFile file = fileRequest.getFile(prmName);
					if (file.isEmpty()) {
						continue;
					}

                    String uploadCategory = request.getParameter("uploadCategory");


				    if (file.getSize() > maxUploadSize) {
						uploadMsg = "err001";
						continue;
					}
					String fileName = file.getOriginalFilename();
					FileInfo fileInfo = new FileInfo(uploadCategory, fileName);
					File pfile = null;

						filePath = getFullFilePath(fileInfo.getRelativePathAndName());
						pfile = new File(filePath);
						if (pfile.exists())
                            pfile.delete();

					pfile.mkdirs();
					file.transferTo(pfile);

                    ZipHelper zipHelper=new ZipHelper();
                        zipHelper.decompress(filePath,
                                ConfigUtil.getInstance().getStoreFrontInstallationPath()+"/themes/"+fileInfo.fileNameOnly);
				}
			} catch (Throwable ex) {
			    uploadMsg = "err002";
				logger.error("Unexpected error when handling uploaded file %1, cause is: %2.", ex);
			} finally {
				if (fileRequest != null) {
					multipartResolver.cleanupMultipart(fileRequest);
				}
			}
		} else {
		    uploadMsg = "err002";
			logger.warn("Invalid request, MultipartHttpServletRequest expected, found: "
		                    + request.getClass().getName()
		                    + ".\n"+ RequestUtil.getRequestInfo(request));
		}


      return new ModelAndView("redirect:/content/theme.html");
	}

}
